package com.yangkunhong.dao;

import com.yangkunhong.pojo.PageDataResponse;
import com.yangkunhong.pojo.User;
import com.yangkunhong.pojo.UserLog;
import com.yangkunhong.requestVo.UserLogVo;
import com.yangkunhong.utils.BeanUtils;
import com.yangkunhong.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

public class UserLogDao extends BaseDao{

    public static boolean addUserLog(UserLog userLog){
        String insertSQL =
                "INSERT INTO user_log(userId,createAt,createIp,op,userAgent)" +
                        "VALUES(?,?,?,?,?)";

        boolean insert = BaseDao.insert(insertSQL, new Object[]{
                userLog.getUserId(),
                userLog.getCreateAt(),
                userLog.getCreateIp(),
                userLog.getOp(),
                userLog.getUserAgent()
        });
        return insert;
    }
    /*
    * 获取日表分页数据，返回PageDataResponse包含 数据列表和数据总数量
    * */

    public static PageDataResponse<List<UserLog>> findUserLogListByUsername(UserLogVo userLogVo){
        //第一步获取数据连接池的资源
        DataSource dataSource = DBUtils.getDataSource();
        //第二步创建QueryRunner的查询构造器
        QueryRunner queryRunner = new QueryRunner(dataSource);
        //第三步 编写SQL
        //如果直接带入参数值，容易造成SQL注入
        //用?占位符表示参数，有几个参数得几个问号
        //用?占位符表示参数，有几个参数得几个问号
        //用?占位符表示参数，有几个参数得几个问号
        String baseSql = "SELECT count(1) FROM user_log ";
        String selectSQL = "SELECT * FROM user_log ";
        String substring = "";
        List<String> list = new ArrayList<>();
        try {
            Map<String, Object> stringObjectMap = BeanUtils.toMap(userLogVo);
            // 定义你想要保留的key的集合
            Set<String> keysToKeep = new HashSet<>(Arrays.asList("limit", "page"));
            StringBuffer stringBuffer = new StringBuffer(" WHERE ");
            for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
                if (!keysToKeep.contains(entry.getKey())) {
                    if(entry.getKey() == "createAt"){
                        stringBuffer.append(entry.getKey()).append(" >= ?").append(" AND ");
                        list.add(String.valueOf(entry.getValue()).trim());
                    }else if(entry.getKey() == "username"){
                        User user = new User();
                        user.setUsername(userLogVo.getUsername());
                        User userByUsername = UserDao.findUserByUsername(user);
                        stringBuffer.append(" userId = ?").append(" AND ");
                        if(userByUsername !=null){
                            list.add(String.valueOf(userByUsername.getId()).trim());
                        }else{
                            list.add(String.valueOf(0).trim());
                        }
                    } else{
                        stringBuffer.append(entry.getKey()).append(" = ?").append(" AND ");
                        list.add(String.valueOf(entry.getValue()).trim());
                    }

                }
            }
            if(list.size()>0) substring = stringBuffer.substring(0, stringBuffer.length() - 5);


        } catch (IllegalAccessException e) {
            baseSql = "SELECT count(1) FROM user_log ";
            selectSQL = "SELECT * FROM user_log  LIMIT ?,? ";
           // e.printStackTrace();
        }
       // list.add(String.valueOf((userLogVo.getPage()-1)*userLogVo.getLimit()));
       // list.add(String.valueOf(userLogVo.getLimit()));

        List<UserLog> userList = null;
        Long count = 0L;
        selectSQL += substring + " LIMIT "+((userLogVo.getPage()-1)*userLogVo.getLimit())+","+userLogVo.getLimit();
        baseSql += substring;

        try {
            userList = queryRunner.query(selectSQL, new BeanListHandler<>(UserLog.class),list.toArray());
            count = queryRunner.query(baseSql, new ScalarHandler<>(),list.toArray());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        PageDataResponse<List<UserLog>> dataResponse = new PageDataResponse<>();
        dataResponse.setCount(count.intValue());
        dataResponse.setData(userList);
        return dataResponse;
    }
    public static boolean deleteById(int id){
        DataSource dataSource = DBUtils.getDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        String updateSQL = "DELETE FROM user_log  WHERE id=?";
        int update = 0;
        try {
            update = queryRunner.update(updateSQL, id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update==1;
    }

    public static UserLog getOneById(int id) {
        //第一步获取数据连接池的资源
        DataSource dataSource = DBUtils.getDataSource();
        //第二步创建QueryRunner的查询构造器
        QueryRunner queryRunner = new QueryRunner(dataSource);
        //第三步 编写SQL
        //如果直接带入参数值，容易造成SQL注入
        //用?占位符表示参数，有几个参数得几个问号
        //用?占位符表示参数，有几个参数得几个问号
        //用?占位符表示参数，有几个参数得几个问号
        String selectSQL = "SELECT * FROM user_log WHERE id=? ";
        //第四步 调用对应的API
        UserLog userLog = null;
        try {
            //new BeanHandler<>(User.class) 表示查询结果自动封装为单个User对象实例
            userLog = queryRunner.query(selectSQL, new BeanHandler<>(UserLog.class), id);
        } catch (SQLException throwables) {
            System.out.println("根据ID获取日志查询失败");
            throwables.printStackTrace();
        }
        return  userLog;
    }
    //修改密码

    public static int update(UserLog userLog){
        DataSource dataSource = DBUtils.getDataSource();
        QueryRunner queryRunner = new QueryRunner(dataSource);
        String updateSQL = "UPDATE user_log SET userId=?,createAt=?,createIp=?,op=?,userAgent=? WHERE id=?";
        int update = 0;
        try {
            update = queryRunner.update(updateSQL, userLog.getUserId(),userLog.getCreateAt(),userLog.getCreateIp(),userLog.getOp(),userLog.getUserAgent(),userLog.getId());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update;
    }


}
